package com.liaowei.file.controller;

import com.liaowei.file.config.MinioConfig;
import com.liaowei.file.utils.MinioUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class FileController {

    private final MinioUtil minioUtil;
    private final MinioConfig prop;


    @PostMapping("/contentUpload")
    public Map contentUpload(MultipartFile file) {
        String objectName = minioUtil.upload(file);
        Map<String, Object> map = new HashMap<>();
        if (null != objectName) {
            Map<String, String> data = new HashMap<>();
            data.put("url", prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
            data.put("alt", file.getOriginalFilename());
            data.put("href", "");

            map.put("errno", 0);
            map.put("data", data);
        } else {
            map.put("errno", 1);
            map.put("message", "上传失败");
        }
        return map;
    }

    @PostMapping("/upload")
    public Map upload(MultipartFile file) {
        String objectName = minioUtil.upload(file);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", null);
        if (null != objectName) {
            map.put("code", 200);
            map.put("data", prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
        }
        return map;
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
    }
}
